package com.laot.searchManage.interceptor;

import com.laot.searchManage.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.laot.seacher_master.model.common.ErrorCode;
import org.laot.seacher_master.model.entity.User;
import org.laot.seacher_master.model.exception.BusinessException;
import org.laot.searchManage.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义JWT拦截器
 * @author laoT
 * @date 2024/1/25
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Value("${jwt.tokenHeader}")
    private String headerStr;
    @Value("${jwt.secret}")
    private String secret;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是feign
        String isFeign = request.getHeader("feign");
        if(StringUtils.isNotBlank(isFeign)){
            //是feign请求
            return true;
        }
        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String token = request.getHeader(headerStr);
        //校验token
        if(StringUtils.isBlank(token)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //判断token是否已过期
        boolean tokenExpired = jwtUtils.isTokenExpired(token);
        if(tokenExpired){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //解析token，拿到用户账号
        String userAccount = jwtUtils.getUserAccountFromToken(token);
        //从Redis中拿到该用户存的token
        String tokenInRedis = (String) redisTemplate.opsForValue().get(RedisConstant.LOGIN_USER+userAccount);
        if(tokenInRedis == null){
            //用户token已过期
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //对比是否为同个token
        if(!tokenInRedis.equals(token)){
            //说明用户已第二次登录，可能在其他浏览器进行的登录
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return true;
    }
}
